﻿using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Sustainalytics.Claims;
using Sustainalytics.DataLayer.ConnectionStrings;
using Sustainalytics.Entities.ConnectionStrings;
using Sustainalytics.Governance.BusinessLogic;
using Sustainalytics.Utils;
using System.Web.Http.Cors;

namespace Sustainalytics.Governance.Service
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    //[AutoInvalidateCacheOutput]
    //[ClaimsChecker("api/v1/governance")]
    [RoutePrefix("api/v1/company")]
    [LogControllerFilter(true, true, false)]
	public class GovernanceCompanyController : ApiController
	{
        private IGovernanceManager _gManager;
        static IClaimsChecker _claimsChecker;
        private string _baseUrl;

	    public GovernanceCompanyController()
	    {
            var connectionString = ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;
            var connectionStringsManager =
                ConnectionStringsManager.GetInstance(ConnectionStringsRepository.GetInstance(connectionString));
            var clientWarehouseConnectionString = connectionStringsManager.GetConnectionString(ConnectionStringType.ClientDW);
            var governanceWarehouseConnectionString = connectionStringsManager.GetConnectionString(ConnectionStringType.GovernanceDW);
            var connectionStringGovernanceInputFile = ConfigurationManager.ConnectionStrings["GovernanceInputFile"].ConnectionString;

            _baseUrl = ConfigurationManager.AppSettings["ClientPlatformUrl"];
            _gManager = GovernanceManager.CreateGovernanceManager(clientWarehouseConnectionString, governanceWarehouseConnectionString, connectionStringGovernanceInputFile);

            
	    }

        static GovernanceCompanyController()
        {
            _claimsChecker = new ClaimsChecker();
        }

        public GovernanceCompanyController(IGovernanceManager gManager, IClaimsChecker claimsChecker, string baseUrl)
        {
            _baseUrl = baseUrl;
            _gManager = gManager;
            _claimsChecker = claimsChecker;
        }

        // [CacheOutput(ServerTimeSpan = 100, ClientTimeSpan = 0, NoCache = true, MustRevalidate = true, Private = true)]
        [Route("{id}")]
        public HttpResponseMessage Get(Guid id)
        {
            try
            {
                var corpData = _gManager.GetCorporateDataById(id);
                if (corpData == null)
                    return Request.CreateResponse(HttpStatusCode.NotFound);

                return Request.CreateResponse(HttpStatusCode.OK, corpData);
            }
            catch (Exception ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }
	}
}

